package com.itqf.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itqf.entity.SysUser;
import com.itqf.entity.dto.SysDtoLogin;
import com.itqf.service.SysUsersService;
import com.itqf.utils.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author 徐老板
 * @date 2020/1/25   13:02
 */
@RestController
public class SysUsersController {
    @Autowired
    SysUsersService sysUsersService;
    @Resource
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("/findall")
    private List<SysUser> findAll(){
        return sysUsersService.findAll();
    }

    @RequestMapping("/sys/login")
    @ResponseBody
    private R login(@RequestBody SysDtoLogin sysDtoLogin){
        if (StringUtils.isEmpty(sysDtoLogin.getCaptcha())||!sysDtoLogin.getCaptcha().equalsIgnoreCase(ShiroUtils.getCode())){
            return R.error("验证码填写错误");
        }
//        R login = sysUsersService.login(sysDtoLogin);
        try {
            Md5Hash md5Hash=new Md5Hash(sysDtoLogin.getPassword(),sysDtoLogin.getUsername(),1024);
            String newPassWord=md5Hash.toString();
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(sysDtoLogin.getUsername(),newPassWord );
            if (sysDtoLogin.isRememberMe()){
                token.setRememberMe(true);
            }
            subject.login(token);



//        验证是否有权限
//            System.out.println("controller层判断是否有这个角色"+subject.hasRole("管理员"));

            return R.ok();
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }

    }

    @RequestMapping("/sys/user/list")
    private ResultData findUserByPage(Pager pager, String search, Sorter sorter){
        return sysUsersService.userByPage(pager,search ,sorter );
    }

    @RequestMapping("/sys/user/info")
    private R returnShiroUser(){

        Subject subject = SecurityUtils.getSubject();
        SysUser token = (SysUser) subject.getPrincipal();
        if (token!=null){
            //不是放这个阈中 是放R的阈中
            subject.getSession().setAttribute("user",token );
            return R.ok().put("user",token );
        }else {
            return R.error("用户信息未存入shiro");
        }
    }

    @RequestMapping("/captcha.jpg")
    private void getKaptcha(HttpServletResponse response){

        String text = defaultKaptcha.createText();//生成验证码文本
        System.out.println("验证码为："+text);
        ShiroUtils.setCode("code",text );
        BufferedImage image = defaultKaptcha.createImage(text);//生成验证码图片

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            //通过这个类把生成的验证码发送到客户端
            ImageIO.write(image,"jpg" , outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/sys/poi")
    private void exportPoi(HttpServletResponse response){

        try {
            response.setContentType("application/octet-stream");
            String filename="测试导出.xls";
             filename = URLEncoder.encode(filename, "utf-8");
            response.setHeader("content-disposition","attactment;filename="+ filename);

            List<Map<String, Object>> mapList = sysUsersService.exportPoi();
            Workbook workbook=new HSSFWorkbook();
            Sheet sheet = workbook.createSheet("员工信息统计表");
            String titles="username,password,email,mobile,sex";

            for (int i = 0; i <mapList.size() ; i++) {
                Row row = sheet.createRow(i);
                String[] split = titles.split(",");
                Map<String, Object> map = mapList.get(i);
                for (int j = 0; j <split.length ; j++) {
                    Cell cell = row.createCell(j);
                    cell.setCellValue(map.get(split[j])+"");
                }
            }
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




}
